﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Configuration;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using LiuYan.Entity;
using LiuYan.Interface;
 using LiuYan.Service;
using LiuYan.Web.Controllers;

namespace LiuYan.Web.Areas.Mall.Controllers
{
    public class OrderController : BaseController
    {

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public ActionResult OrderList(int sid)
        {
            var status = "";
            for (int i = 1; i <= 5; i++)
            {
                status += new OrderService().OrderStatusCount(i, UserInfo().Id) + ",";
            }
            status = status.Substring(0, status.Length - 1);
            ViewData["status"] = status;
            ViewData["sid"] = sid;
            return View();
        }

        public ActionResult OrderFoodList(int status)
        {
            ViewData["status"] = status;
            return View();
        }
        
        /// <summary>
        /// 支付页面
        /// </summary>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public ActionResult Pay(string orderno)
        {
                ViewData["address"] = new AddressService().GetAddress(UserInfo().Id);
                var set = new OrderService().GetOneOrder(orderno);
                ViewData["orderno"] = orderno;
                ViewData["orderinfo"] = set;
                double temp = Convert.ToDouble(set.Tables[0].Rows[0]["TotalPrice"]) * 100; //总价
                var price = Convert.ToInt32(temp);
                ViewData["price"] = price; 
             
            return View();
        }

        public ActionResult StartPay(string orderno)
        {  ViewData["orderno"] = orderno;
           ViewData["status"] = "0";
            if (orderno.Contains("sp"))
            {
                var set = new OrderService().GetOneOrder(orderno);
                double temp = Convert.ToDouble(set.Tables[0].Rows[0]["TotalPrice"]) * 100; //总价
                var price = Convert.ToInt32(temp);
                ViewData["price"] = price;
                ViewData["parameter"] = GetPayParameters(orderno, price);

            }
            return View();
        }


        public string GetOrder(int sid,int pageIndex,int pageCount)
        {
            return JsonConvert.SerializeObject(new OrderService().GetOrder(sid,pageIndex,pageCount,UserInfo().Id));
        }

        public ActionResult Evaluate(int id, string orderno)
        {
            ViewData["id"] = id;
            ViewData["orderno"] = orderno;
            ViewData["goodinfo"] = new GoodService().GetgPjInfo(id);
            return View();
        }

        public int CPj(int id, string orderno)
        {
            return new EvaluateService().CheckPj(id, orderno);
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        public int DelOrder(string oid)
        {
            OrderService orderService=new OrderService();
            var id=orderService.GetOrderIdOrNo(oid, "id");
            return orderService.DelOrder(Convert.ToInt32(id));
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public string UploadImg()
        {
            HttpFileCollection file = System.Web.HttpContext.Current.Request.Files;
            int num = file.Count;
            string imgPath = "";
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string fileName = file[0].FileName.Split('\\').Last();
            imgPath = "/Content/pjimg/" + Convert.ToInt64(ts.TotalSeconds) + "." + fileName.Split('.').Last();
            string path = Server.MapPath(imgPath);
            file[0].SaveAs(path);
            return "{'status':'1','path':'" + imgPath + "'}";
        }

        public int EditPingJian(FormCollection form)
        {
            var img = form["img"].Split(',');
            TB_Evaluate entity=new TB_Evaluate();
            entity.Id = Convert.ToInt32(form["id"]);
            entity.Gid = Convert.ToInt32(form["gid"]);
            entity.Rnk = Convert.ToInt32(form["rnk"]);
            entity.Img1 = img.Length >= 1 ? img[0] : "";
            entity.Img2 = img.Length >= 2 ? img[1] : "";
            entity.Img3 = img.Length >= 3 ? img[2] : "";
            entity.Date = DateTime.Now;
            entity.Del = 0;
            entity.UserId = UserInfo().Id;
            entity.Text = form["content"];
            entity.OrderNo = form["orderno"];
            entity.PlName = "";
            return new EvaluateService().Edit(entity);
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public int EditOrderStatus(string orderid,int value)
        {
            return new OrderService().EditOrderStatus(orderid, value);
        }

        /// <summary>
        /// 收货
        /// </summary>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public int ShouHuo(string orderno)
        {
            return new OrderService().ShouHuo(orderno);
        }

        /// <summary>
        /// 修改订单地址
        /// </summary>
        /// <param name="addid"></param>
        /// <param name="orderno"></param>
        /// <returns></returns>
        public int EditAdd(int addid,string orderno)
        {
            return new OrderService().EditAdd(addid, orderno);
        }
        /// <summary>
        /// 微信JSAPI支付
        /// </summary>
        /// <param name="orderno"></param>
        /// <param name="price"></param>
        /// <returns></returns>
        public string GetPayParameters(string orderno,int price)
        {
            var str = new WxPay().TyPay(orderno, UserInfo().OpenId, price);//微信统一支付接口返回 prepay_id
           //  WriteMess(str);
            //构造需要用SHA1算法加密的数据
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("appId", WxEntity.appid);
            dic.Add("timeStamp", new Common().GenerateTimeStamp());//当前时间戳
            dic.Add("nonceStr", new Common().GenerateNonceStr());//随机字符串（32位）
            dic.Add("package", "prepay_id=" +str);
            dic.Add("signType", "MD5");//签名方式 MD加密算法5
            string paysign = new Common().GetSign(dic, WxEntity.key);//获取签名
            dic.Add("paySign", paysign);
            return JsonConvert.SerializeObject(dic);
        }

        public void WriteMess(string mess)
        {

            string realPath = Server.MapPath("//rizhi.txt");//真正的地址
            FileStream fsWriter = null;//公开以文件为主的流
            if (!System.IO.File.Exists(realPath))
            {
                fsWriter = new FileStream(realPath, FileMode.Create);
            }
            else
            {
                fsWriter = new FileStream(realPath, FileMode.Append);
            }
            StreamWriter sw = new StreamWriter(fsWriter);//实现一个类，向流中写入字符
            sw.WriteLine(mess);//写入流
            sw.Close();//类关闭
            fsWriter.Close();//流关闭
        }

        public string CloseOrder(string orderno)
        {
            var str= new WxPay().CloseOrder(orderno);
            WriteMess("close:"+str);
            return str;
        }
    }
}
